/**
 * 文档批量替换工具 JavaScript
 */

// 全局变量
let uploadedFiles = [];  // 存储已上传的文件名列表
let batchId = '';  // 当前批次的唯一ID
let editableRules = [];  // 可编辑的规则列表

$(document).ready(function() {
    // 切换上传模式
    $('input[name="uploadMode"]').on('change', function() {
        if ($(this).val() === 'files') {
            $('#docFiles').removeClass('d-none').prop('required', true);
            $('#docFolder').addClass('d-none').prop('required', false);
            $('#fileList').html('');
        } else {
            $('#docFiles').addClass('d-none').prop('required', false);
            $('#docFolder').removeClass('d-none').prop('required', true);
            $('#fileList').html('');
        }
    });
    
    // 切换替换模式
    $('input[name="replaceMode"]').on('change', function() {
        if ($(this).val() === 'single') {
            $('#singleReplacePanel').removeClass('d-none');
            $('#batchRulesPanel').addClass('d-none');
            $('#findText').prop('required', true);
            $('#replaceText').prop('required', true);
            $('#rulesFile').prop('required', false);
        } else {
            $('#singleReplacePanel').addClass('d-none');
            $('#batchRulesPanel').removeClass('d-none');
            $('#findText').prop('required', false);
            $('#replaceText').prop('required', false);
            // 更新UI状态
            updateRulesFileUI(editableRules.length > 0);
        }
    });
    
    // 显示选择的文件列表（单文件模式）
    $('#docFiles').on('change', function() {
        displayFileList(this.files);
    });
    
    // 显示选择的文件列表（文件夹模式）
    $('#docFolder').on('change', function() {
        displayFileList(this.files);
    });
    
    // 预览替换规则文件（手动上传）
    $('#rulesFile').on('change', function() {
        const file = this.files[0];
        if (!file) {
            $('#rulesPreview').html('');
            editableRules = [];
            updateRulesFileUI(false);
            return;
        }
        
        // 使用相同的加载函数，这样手动上传的规则也可以编辑
        loadRulesFileContent(file);
        
        // 更新UI显示规则已手动上传
        updateRulesFileUI(true);
    });
    
    // 批量替换表单提交
    $('#replaceForm').on('submit', handleFormSubmit);
});

// HTML转义函数
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}

// 显示提示消息
function showToast(message) {
    const toast = $(`
        <div class="position-fixed top-0 start-50 translate-middle-x mt-3" style="z-index: 9999;">
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
    `);
    
    $('body').append(toast);
    
    setTimeout(() => {
        toast.fadeOut(300, function() {
            $(this).remove();
        });
    }, 3000);
}

// 全局函数：切换规则详情显示
window.toggleRuleDetails = function(index) {
    const detailsRow = $(`#rule-details-${index}`);
    const icon = $(`#icon-${index}`);
    
    if (detailsRow.hasClass('d-none')) {
        detailsRow.removeClass('d-none');
        icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
    } else {
        detailsRow.addClass('d-none');
        icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
    }
};

// 统一的文件列表显示函数
function displayFileList(files) {
    if (files.length === 0) {
        $('#fileList').html('');
        return;
    }
    
    // 分类文件
    const docxFiles = [];
    let rulesFile = null;
    const otherFiles = [];
    
    Array.from(files).forEach(file => {
        const filename = file.name;
        if (filename === "0_过程文档批量替换信息.txt") {
            rulesFile = file;
        } else if (filename.endsWith('.docx')) {
            docxFiles.push(file);
        } else {
            otherFiles.push(file);
        }
    });
    
    if (docxFiles.length === 0 && !rulesFile) {
        $('#fileList').html('<div class="alert alert-warning">未找到支持的文件（需要 .docx 文件）</div>');
        return;
    }
    
    let fileListHtml = '<div class="alert alert-info">';
    
    // 显示规则文件信息
    if (rulesFile) {
        const relativePath = rulesFile.webkitRelativePath || rulesFile.name;
        fileListHtml += `
            <div class="mb-2 p-2 bg-success bg-opacity-10 rounded border border-success">
                <strong><i class="fas fa-file-alt text-success"></i> 检测到替换规则文件：</strong>
                <div class="ms-3 mt-1">
                    <code>${relativePath}</code> (${(rulesFile.size / 1024).toFixed(2)} KB)
                </div>
            </div>
        `;
        
        // 自动切换到批量替换规则模式
        $('#batchRules').prop('checked', true).trigger('change');
        
        // 读取并显示规则文件内容
        loadRulesFileContent(rulesFile);
        
        // 更新UI显示规则已自动加载
        updateRulesFileUI(true);
    }
    
    // 显示文档文件列表
    if (docxFiles.length > 0) {
        fileListHtml += '<strong><i class="fas fa-file-word text-primary"></i> 已选择 ' + docxFiles.length + ' 个Word文档:</strong>';
        fileListHtml += '<div class="mt-2" style="max-height: 300px; overflow-y: auto;"><ul class="mb-0">';
        
        docxFiles.forEach(file => {
            const relativePath = file.webkitRelativePath || file.name;
            fileListHtml += `<li>${relativePath} (${(file.size / 1024).toFixed(2)} KB)</li>`;
        });
        
        fileListHtml += '</ul></div>';
    }
    
    // 显示不支持的文件
    if (otherFiles.length > 0) {
        fileListHtml += `
            <div class="mt-2 p-2 bg-warning bg-opacity-10 rounded border border-warning">
                <small class="text-warning">
                    <i class="fas fa-exclamation-triangle"></i> 
                    ${otherFiles.length} 个文件将被忽略（不支持的格式）
                </small>
            </div>
        `;
    }
    
    fileListHtml += '</div>';
    $('#fileList').html(fileListHtml);
}

// 读取规则文件内容
function loadRulesFileContent(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const content = e.target.result;
        const lines = content.split('\n');
        
        // 解析规则
        editableRules = [];
        lines.forEach((line, index) => {
            line = line.trim();
            // 跳过空行和注释
            if (!line || line.startsWith('#')) {
                return;
            }
            
            const parts = line.split(':');
            if (parts.length >= 2) {
                const findText = parts[0].trim();
                const replaceText = parts.slice(1).join(':').trim();
                
                if (findText) {
                    editableRules.push({
                        find: findText,
                        replace: replaceText,
                        line_num: editableRules.length + 1
                    });
                }
            }
        });
        
        // 显示规则预览（可编辑）
        displayLoadedRulesInPanel();
    };
    
    reader.onerror = function() {
        $('#rulesPreview').html(`
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i> 读取规则文件失败
            </div>
        `);
    };
    
    reader.readAsText(file, 'utf-8');
}

// 在规则面板中显示加载的规则（可编辑版）
function displayLoadedRulesInPanel() {
    if (editableRules.length === 0) {
        $('#rulesPreview').html(`
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i> 规则文件中没有找到有效的替换规则
            </div>
        `);
        return;
    }
    
    let previewHtml = `
        <div class="alert alert-success">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <strong>
                    <i class="fas fa-check-circle"></i> 
                    已自动加载 <span id="autoLoadedRulesCount">${editableRules.length}</span> 条替换规则
                </strong>
                <button type="button" class="btn btn-sm btn-primary" onclick="toggleAutoLoadedRulesEdit()">
                    <i class="fas fa-edit"></i> 编辑规则
                </button>
            </div>
            
            <!-- 只读视图 -->
            <div id="autoLoadedRulesReadView" style="max-height: 300px; overflow-y: auto;">
                <table class="table table-sm table-bordered mb-0 bg-white">
                    <thead>
                        <tr>
                            <th width="50">#</th>
                            <th width="45%">查找内容</th>
                            <th width="45%">替换为</th>
                        </tr>
                    </thead>
                    <tbody id="autoLoadedRulesReadBody">
    `;
    
    editableRules.forEach((rule, index) => {
        previewHtml += `
            <tr>
                <td class="text-center">${rule.line_num}</td>
                <td><code>${escapeHtml(rule.find)}</code></td>
                <td><code>${escapeHtml(rule.replace)}</code></td>
            </tr>
        `;
    });
    
    previewHtml += `
                    </tbody>
                </table>
            </div>
            
            <!-- 可编辑视图 -->
            <div id="autoLoadedRulesEditView" class="d-none">
                <div class="mb-2">
                    <button type="button" class="btn btn-sm btn-success" onclick="addAutoLoadedRule()">
                        <i class="fas fa-plus"></i> 添加规则
                    </button>
                    <button type="button" class="btn btn-sm btn-warning" onclick="saveAutoLoadedRulesEdit()">
                        <i class="fas fa-save"></i> 保存修改
                    </button>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="cancelAutoLoadedRulesEdit()">
                        <i class="fas fa-times"></i> 取消
                    </button>
                </div>
                <div style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-bordered mb-0 bg-white">
                        <thead>
                            <tr>
                                <th width="50">#</th>
                                <th width="40%">查找内容</th>
                                <th width="40%">替换为</th>
                                <th width="80px" class="text-center">操作</th>
                            </tr>
                        </thead>
                        <tbody id="autoLoadedRulesEditBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    $('#rulesPreview').html(previewHtml);
}

// 切换规则编辑模式
window.toggleAutoLoadedRulesEdit = function() {
    $('#autoLoadedRulesReadView').addClass('d-none');
    $('#autoLoadedRulesEditView').removeClass('d-none');
    renderEditableRules();
};

// 渲染可编辑的规则表格
function renderEditableRules() {
    let tableHtml = '';
    editableRules.forEach((rule, index) => {
        tableHtml += `
            <tr data-rule-index="${index}">
                <td class="text-center align-middle">${index + 1}</td>
                <td>
                    <input type="text" class="form-control form-control-sm" 
                           value="${escapeHtml(rule.find)}" 
                           onchange="updateAutoLoadedRule(${index}, 'find', this.value)">
                </td>
                <td>
                    <input type="text" class="form-control form-control-sm" 
                           value="${escapeHtml(rule.replace)}" 
                           onchange="updateAutoLoadedRule(${index}, 'replace', this.value)">
                </td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-danger" 
                            onclick="deleteAutoLoadedRule(${index})" title="删除此规则">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    $('#autoLoadedRulesEditBody').html(tableHtml);
}

// 更新规则
window.updateAutoLoadedRule = function(index, field, value) {
    if (editableRules[index]) {
        editableRules[index][field] = value;
    }
};

// 删除规则
window.deleteAutoLoadedRule = function(index) {
    if (confirm('确定要删除这条规则吗？')) {
        editableRules.splice(index, 1);
        renderEditableRules();
        $('#autoLoadedRulesCount').text(editableRules.length);
    }
};

// 添加新规则
window.addAutoLoadedRule = function() {
    editableRules.push({
        find: '',
        replace: '',
        line_num: editableRules.length + 1
    });
    renderEditableRules();
    $('#autoLoadedRulesCount').text(editableRules.length);
    
    // 滚动到底部并聚焦
    setTimeout(() => {
        const editView = $('#autoLoadedRulesEditView div[style*="overflow-y"]');
        if (editView.length) {
            editView.scrollTop(editView[0].scrollHeight);
        }
        $('#autoLoadedRulesEditBody tr:last input:first').focus();
    }, 100);
};

// 保存规则编辑
window.saveAutoLoadedRulesEdit = function() {
    // 过滤掉空规则
    editableRules = editableRules.filter(rule => rule.find.trim() !== '');
    
    // 重新编号
    editableRules.forEach((rule, index) => {
        rule.line_num = index + 1;
    });
    
    if (editableRules.length === 0) {
        alert('至少需要保留一条规则！');
        return;
    }
    
    // 更新只读视图
    updateRulesReadView();
    
    // 切换回只读视图
    $('#autoLoadedRulesEditView').addClass('d-none');
    $('#autoLoadedRulesReadView').removeClass('d-none');
    
    // 更新规则数量和UI状态
    $('#autoLoadedRulesCount').text(editableRules.length);
    updateRulesFileUI(editableRules.length > 0);
    
    showToast('规则已保存，共 ' + editableRules.length + ' 条规则');
};

// 取消规则编辑
window.cancelAutoLoadedRulesEdit = function() {
    if (confirm('确定要取消编辑吗？所有未保存的修改将丢失。')) {
        $('#autoLoadedRulesEditView').addClass('d-none');
        $('#autoLoadedRulesReadView').removeClass('d-none');
    }
};

// 更新只读视图
function updateRulesReadView() {
    let tableHtml = '';
    editableRules.forEach((rule) => {
        tableHtml += `
            <tr>
                <td class="text-center">${rule.line_num}</td>
                <td><code>${escapeHtml(rule.find)}</code></td>
                <td><code>${escapeHtml(rule.replace)}</code></td>
            </tr>
        `;
    });
    $('#autoLoadedRulesReadBody').html(tableHtml);
}

// 更新规则文件UI状态
function updateRulesFileUI(hasRules) {
    if (hasRules) {
        // 显示"已自动加载"标记
        $('#rulesAutoLoaded').removeClass('d-none');
        $('#rulesFileRequired').addClass('d-none');
        
        // 切换提示文本
        $('#rulesFileHint').addClass('d-none');
        $('#rulesAutoLoadedHint').removeClass('d-none');
        
        // 移除必填属性
        $('#rulesFile').prop('required', false);
        
        // 添加视觉提示
        $('#rulesFile').addClass('border-success');
    } else {
        // 隐藏"已自动加载"标记
        $('#rulesAutoLoaded').addClass('d-none');
        $('#rulesFileRequired').removeClass('d-none');
        
        // 切换提示文本
        $('#rulesFileHint').removeClass('d-none');
        $('#rulesAutoLoadedHint').addClass('d-none');
        
        // 恢复必填属性（如果是批量模式且没有规则）
        const isBatchMode = $('input[name="replaceMode"]:checked').val() === 'batch';
        $('#rulesFile').prop('required', isBatchMode && editableRules.length === 0);
        
        // 移除视觉提示
        $('#rulesFile').removeClass('border-success');
    }
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    // 清空之前的结果
    $('#resultMessage').html('');
    $('#resultDetails').html('');
    
    // 检查批量替换模式下是否有规则
    let replaceMode = $('input[name="replaceMode"]:checked').val();
    if (replaceMode === 'batch') {
        // 检查是否有规则（来自自动检测或手动上传）
        const hasRules = editableRules && editableRules.length > 0;
        const hasRulesFile = $('#rulesFile')[0].files.length > 0;
        
        if (!hasRules && !hasRulesFile) {
            $('#resultMessage').html(`
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> 
                    批量替换模式需要替换规则。请上传替换规则文件，或选择包含"0_过程文档批量替换信息.txt"的文件夹。
                </div>
            `);
            return;
        }
    }
    
    // 获取当前选择的文件
    const uploadMode = $('input[name="uploadMode"]:checked').val();
    const files = uploadMode === 'files' ? $('#docFiles')[0].files : $('#docFolder')[0].files;
    
    if (files.length === 0) {
        $('#resultMessage').html(`
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i> 请先选择文件或文件夹
            </div>
        `);
        return;
    }
    
    // 过滤支持的文件类型（仅支持.docx）
    const supportedFiles = Array.from(files).filter(file => {
        return file.name.endsWith('.docx');
    });
    
    if (supportedFiles.length === 0) {
        $('#resultMessage').html(`
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i> 未找到支持的文件格式（仅支持 .docx）
            </div>
        `);
        return;
    }
    
    // 显示上传进度
    $('#resultMessage').html(`
        <div class="alert alert-info">
            <i class="fas fa-spinner fa-spin"></i> 正在上传 ${supportedFiles.length} 个文件...
        </div>
    `);
    
    // 第一步：上传文件
    const formData = new FormData();
    supportedFiles.forEach(file => {
        // 跳过规则文件，因为已经在前端解析了
        if (file.name === "0_过程文档批量替换信息.txt") {
            return;
        }
        
        formData.append('files', file);
        // 如果是文件夹模式，还需要传递相对路径
        if (uploadMode === 'folder' && file.webkitRelativePath) {
            formData.append('paths', file.webkitRelativePath);
        }
    });
    
    // 如果是批量替换规则模式且手动上传了规则文件（非自动检测），添加规则文件
    if (replaceMode === 'batch' && editableRules.length === 0) {
        const rulesFile = $('#rulesFile')[0].files[0];
        if (rulesFile) {
            formData.append('rules_file', rulesFile);
        }
    }
    
    // 使用window.DOC_REPLACE_URLS来获取URL
    $.ajax({
        url: window.DOC_REPLACE_URLS.upload,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(uploadResponse) {
            if (uploadResponse.success) {
                // 保存批次ID和文件列表
                batchId = uploadResponse.batch_id;
                uploadedFiles = uploadResponse.files.map(f => f.relative_path);
                
                // 显示替换进度
                $('#resultMessage').html(`
                    <div class="alert alert-info">
                        <i class="fas fa-spinner fa-spin"></i> 文件上传成功，正在执行替换...
                    </div>
                `);
                
                // 第二步：执行替换
                executeReplace(replaceMode);
            } else {
                $('#resultMessage').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i> ${uploadResponse.message}
                    </div>
                `);
            }
        },
        error: function(xhr) {
            const errorMsg = xhr.responseJSON?.message || '文件上传失败，请稍后重试';
            $('#resultMessage').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> ${errorMsg}
                </div>
            `);
        }
    });
}

// 执行替换
function executeReplace(replaceMode) {
    const replaceData = {
        use_regex: $('#useRegex').is(':checked'),
        case_sensitive: $('#caseSensitive').is(':checked'),
        batch_id: batchId,
        files: uploadedFiles,
        replace_mode: replaceMode
    };
    
    // 根据替换模式添加不同的参数
    if (replaceMode === 'single') {
        replaceData.find_text = $('#findText').val();
        replaceData.replace_text = $('#replaceText').val();
    } else {
        // 批量替换模式
        // 如果已经在前端加载了规则（自动检测或手动上传），使用前端规则
        if (editableRules && editableRules.length > 0) {
            replaceData.custom_rules = editableRules;
            replaceData.use_custom_rules = true;
        } else {
            // 否则使用后端上传的规则文件
            replaceData.use_rules_file = true;
        }
    }

    $.ajax({
        url: window.DOC_REPLACE_URLS.replace,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(replaceData),
        success: function(replaceResponse) {
            if (replaceResponse.success) {
                displayResults(replaceResponse.results);
            } else {
                $('#resultMessage').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i> ${replaceResponse.message}
                    </div>
                `);
            }
        },
        error: function(xhr) {
            const errorMsg = xhr.responseJSON?.message || '替换失败，请稍后重试';
            $('#resultMessage').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> ${errorMsg}
                </div>
            `);
        }
    });
}

// 显示结果
function displayResults(results) {
    let message = `
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i> 
            替换完成！共处理 ${results.processed_files} 个文件`;
    
    if (results.total_rules > 1) {
        message += `，应用了 ${results.total_rules} 条替换规则`;
    }
    
    message += `，替换了 ${results.total_replacements} 处内容
        </div>
    `;
    
    $('#resultMessage').html(message);
    
    // 显示详细结果和下载链接
    let detailsHtml = `
        <div class="card shadow-sm">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0">
                    <i class="fas fa-file-alt"></i> 文件处理详情
                    <small class="text-muted ms-2">(共 ${results.total_files} 个文件)</small>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-bordered align-middle">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 40%;">
                                    <i class="fas fa-file"></i> 文件名
                                </th>
                                <th style="width: 12%;" class="text-center">
                                    <i class="fas fa-sort-numeric-down"></i> 替换次数
                                </th>
                                <th style="width: 10%;" class="text-center">
                                    <i class="fas fa-info-circle"></i> 状态
                                </th>
                                <th style="width: 18%;" class="text-center">
                                    <i class="fas fa-download"></i> 下载
                                </th>
                                <th style="width: 20%;" class="text-center">
                                    <i class="fas fa-list"></i> 规则详情
                                </th>
                            </tr>
                        </thead>
                        <tbody>
    `;
    
    results.details.forEach(function(item, index) {
        const statusBadge = item.status === 'success' 
            ? '<span class="badge bg-success"><i class="fas fa-check"></i> 成功</span>' 
            : '<span class="badge bg-danger"><i class="fas fa-times"></i> 失败</span>';
        
        // 构建下载链接
        const downloadBtn = item.status === 'success' && item.output_filename
            ? `<a href="${window.DOC_REPLACE_URLS.downloadFile}/${batchId}/${encodeURIComponent(item.output_filename)}" 
                  class="btn btn-sm btn-primary" title="下载处理后的文件">
                  <i class="fas fa-download"></i> 下载文件
               </a>`
            : '<span class="text-muted">-</span>';
        
        // 如果有规则详情，添加展开按钮
        const expandBtn = item.rule_details && item.rule_details.length > 0
            ? `<button class="btn btn-sm btn-outline-info" type="button" 
                       onclick="toggleRuleDetails(${index})" title="查看每条规则的执行情况">
                  <i class="fas fa-chevron-down" id="icon-${index}"></i> 展开详情
               </button>`
            : '<span class="text-muted">-</span>';
        
        const errorMessage = item.message ? `
            <tr>
                <td colspan="5" class="bg-danger bg-opacity-10 p-2">
                    <small class="text-danger">
                        <i class="fas fa-exclamation-triangle"></i> 
                        错误信息：${item.message}
                    </small>
                </td>
            </tr>
        ` : '';
        
        detailsHtml += `
            <tr>
                <td>
                    <i class="fas fa-file-alt text-muted me-2"></i>
                    ${item.filename}
                </td>
                <td class="text-center">
                    <span class="badge bg-info">${item.replacements} 处</span>
                </td>
                <td class="text-center">${statusBadge}</td>
                <td class="text-center">${downloadBtn}</td>
                <td class="text-center">${expandBtn}</td>
            </tr>
            ${errorMessage}
        `;
        
        // 添加隐藏的规则详情行
        if (item.rule_details && item.rule_details.length > 0) {
            detailsHtml += buildRuleDetailsRow(item, index);
        }
    });
    
    detailsHtml += `
                        </tbody>
                    </table>
                </div>
    `;
    
    // 如果有成功的文件，显示批量下载按钮
    if (results.output_files && results.output_files.length > 0) {
        detailsHtml += `
            <div class="mt-3 p-3 bg-success bg-opacity-10 rounded">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h6 class="mb-2">
                            <i class="fas fa-check-circle text-success"></i> 
                            <strong>处理完成！</strong>
                        </h6>
                        <p class="mb-0 text-muted">
                            <i class="fas fa-info-circle"></i> 
                            您可以单独下载每个文件，或者一键下载所有文件的ZIP压缩包
                        </p>
                    </div>
                    <div class="col-md-4 text-md-end mt-2 mt-md-0">
                        <a href="${window.DOC_REPLACE_URLS.downloadBatch}/${batchId}" 
                           class="btn btn-success btn-lg shadow">
                            <i class="fas fa-file-archive"></i> 
                            批量下载 ZIP
                            <i class="fas fa-arrow-down ms-1"></i>
                        </a>
                    </div>
                </div>
            </div>
        `;
    }
    
    detailsHtml += `
            </div>
        </div>
    `;
    
    $('#resultDetails').html(detailsHtml);
}

// 构建规则详情行
function buildRuleDetailsRow(item, index) {
    let html = `
        <tr id="rule-details-${index}" class="d-none">
            <td colspan="5" class="bg-light p-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-info bg-opacity-10">
                        <strong class="text-info">
                            <i class="fas fa-list-ol"></i> 
                            规则执行详情（共 ${item.rule_details.length} 条）
                        </strong>
                    </div>
                    <div class="card-body p-2">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered table-striped mb-0 align-middle">
                                <thead class="table-secondary">
                                    <tr>
                                        <th style="width: 10%;" class="text-center">
                                            <i class="fas fa-hashtag"></i> 规则序号
                                        </th>
                                        <th style="width: 35%;">
                                            <i class="fas fa-search"></i> 查找内容
                                        </th>
                                        <th style="width: 35%;">
                                            <i class="fas fa-exchange-alt"></i> 替换为
                                        </th>
                                        <th style="width: 20%;" class="text-center">
                                            <i class="fas fa-calculator"></i> 替换次数
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
    `;
    
    item.rule_details.forEach(function(rule) {
        const countBadge = rule.count > 0 
            ? `<span class="badge bg-success">${rule.count} 次</span>`
            : `<span class="badge bg-secondary">0 次</span>`;
        
        html += `
            <tr>
                <td class="text-center">
                    <span class="badge bg-primary">规则 #${rule.rule_num}</span>
                </td>
                <td>
                    <code class="text-danger">${escapeHtml(rule.find)}</code>
                </td>
                <td>
                    <code class="text-success">${escapeHtml(rule.replace)}</code>
                </td>
                <td class="text-center">${countBadge}</td>
            </tr>
        `;
    });
    
    html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    `;
    
    return html;
}

